package exam.controller;

import com.github.pagehelper.PageInfo;
import exam.bean.Student;
import exam.bean.Teacher;
import exam.service.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/teachers")
public class TeacherController {
    @Autowired
    private ITeacherService teacherService;

    @Value("${file.upload.path}")
    private String fileUploadPath;

    @GetMapping("/search")
    public String searchTeachers(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phoneNumber,
            @RequestParam(required = false) String subject,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            Model model) {

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("name", name);
        queryMap.put("phoneNumber", phoneNumber);
        queryMap.put("subject", subject);
        queryMap.put("pageNum", pageNum);
        queryMap.put("pageSize", pageSize);

        List<Teacher> teacherList = teacherService.selectTeacher(queryMap);

        PageInfo<Teacher> pageInfo = new PageInfo<>(teacherList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("teacherList", teacherList);

        return "indexTeacher";
    }

    @RequestMapping(value = "/teacher", method = {RequestMethod.POST,RequestMethod.GET})
    public String queryTeachers(@RequestParam(name = "pageNum", required = false, defaultValue = "1")
                                int pageNum,
                                @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                                int pageSize, @RequestParam Map<String,Object> queryMap, Model model, HttpServletRequest request) {
        //开始分页
        //PageHelper.startPage(pageNum,pageSize);
        queryMap.put("pageNum", pageNum);
        queryMap.put("pageSize", pageSize);
        List<Teacher> teacherList = teacherService.selectTeacher(queryMap);

        model.addAttribute("pageInfo",new PageInfo<>(teacherList));
        model.addAttribute("teacherList",teacherList);
        return "indexTeacher";

    }

    @ResponseBody
    @PostMapping("/add")
    public boolean add(Teacher teacher){
        return teacherService.insertTeacher(teacher)>0?true:false;
    }
    @GetMapping("/toAdd")
    public String toAdd(){

        return "addTeacher";
    }

    @GetMapping("/toUpdate")
    public String toUpdate(int id,Model model){

        Map<String,Object> map=new HashMap<String,Object>();
        map.put("id",id);

        Teacher teacher = teacherService.selectTeacherById(map);

        model.addAttribute("teacher",teacher);

        return "updateTeacher";
    }

    @ResponseBody
    @PostMapping("/update")
    public boolean update(Teacher teacher){

        return teacherService.updateTeacher(teacher)>0?true:false;
    }

    @ResponseBody
    @GetMapping("/delete")
    public boolean delete(int id){
        return teacherService.deleteTeacher(id)>0?true:false;
    }

    @GetMapping("/toDetail")
    public String toDetail(int id,Model model){

        Map<String,Object> map=new HashMap<String,Object>();
        map.put("id",id);

        Teacher teacher = teacherService.selectTeacherById(map);

        model.addAttribute("teacher",teacher);

        return "detailTeacher";
    }

    @PostMapping("/uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (file != null && !file.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                String newFileName = UUID.randomUUID().toString() + 
                    originalFilename.substring(originalFilename.lastIndexOf("."));
                
                File targetFile = new File(fileUploadPath);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                
                file.transferTo(new File(fileUploadPath + newFileName));
                
                result.put("code", 0);
                result.put("msg", "上传成功");
                result.put("fileName", newFileName);
                result.put("originalFileName", originalFilename);
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "上传失败：" + e.getMessage());
        }
        return result;
    }

    @GetMapping("/downloadFile")
    public void downloadFile(String fileName, String originalFileName, 
            HttpServletResponse response) {
        try {
            File file = new File(fileUploadPath + fileName);
            if (file.exists()) {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", 
                    "attachment;filename=" + URLEncoder.encode(originalFileName, "UTF-8"));
                
                Files.copy(file.toPath(), response.getOutputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/deleteFile")
    @ResponseBody
    public Map<String, Object> deleteFile(String fileName) {
        Map<String, Object> result = new HashMap<>();
        try {
            File file = new File(fileUploadPath + fileName);
            if (file.exists() && file.delete()) {
                result.put("code", 0);
                result.put("msg", "删除成功");
            } else {
                result.put("code", 1);
                result.put("msg", "文件不存在或删除失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "删除失败：" + e.getMessage());
        }
        return result;
    }
}
